package com.jyniubi.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.jyniubi.base.exception.BussinessException;
import com.jyniubi.base.result.ResponseEnum;
import com.jyniubi.oss.properties.OssProperties;
import com.jyniubi.oss.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file,String module) {
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
//        String filePath= "C:\\Users\\zjy\\Pictures\\Saved Pictures\\2.jpg";
        String filePath= file.getOriginalFilename();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = module + new DateTime().toString("yyyy/MM/dd/")+System.currentTimeMillis()+"_"
                + UUID.randomUUID().toString().substring(0,6)
                +filePath.substring(filePath.lastIndexOf("."));
        // 创建OSSClient实例。//可以操作账户的桶文件
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.ACCESSKEYID, OssProperties.ACCESSKEYSECRET);
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            //参数1：桶名，参数2：上传的文件保存到oss桶中的路径+文件名   参数3:要上传的文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssProperties.BUCKETNAME, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            if (result != null && result.getResponse() != null && result.getResponse().getStatusCode() != 200){
                log.error("文件传输返回报文状态码",result.getResponse().getStatusCode());
            }
            //https://sh22020828-srb.oss-cn-shanghai.aliyuncs.com/imgs/2023/01/31/1675149588177_f964ba.jpg
            String path = "https://" + OssProperties.BUCKETNAME + ".oss-cn-shanghai.aliyuncs.com/" + objectName;
            return path;
        } catch (Exception ce) {
            log.error("文件上传错误，{}",ce);
            throw new BussinessException(ResponseEnum.UPLOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void delete(String path) {
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        //https://sh22020828-srb.oss-cn-shanghai.aliyuncs.com/imgs/2023/01/31/1675149588177_f964ba.jpg
        //String path = "https://caigou-srb.oss-cn-shanghai.aliyuncs.com/img/2024/05/24/1716542476027_d03279.jpg";
        String objectName = path.substring(path.indexOf("https://" + OssProperties.BUCKETNAME +".oss-cn-shanghai.aliyuncs.com/")
                +("https://" + OssProperties.BUCKETNAME +".oss-cn-shanghai.aliyuncs.com/").length());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.ACCESSKEYID, OssProperties.ACCESSKEYSECRET);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(OssProperties.BUCKETNAME, objectName);
        } catch (Exception ce) {
            throw new BussinessException(ResponseEnum.DELETE_FILE_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
